package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"goods/models"
)

type GoodsController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *GoodsController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	price := c.GetString("price")
	weight := c.GetString("weight")
	num := c.GetString("num")
	time := c.GetString("time")
	goods := models.Goods{
		Name:   name,
		Price:  price,
		Weight: weight,
		Num:    num,
		Time:   time,
	}
	err := models.DB.Create(&goods).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: goods,
		}
		c.ServeJSON()
	}
}

// 列表
func (c *GoodsController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	offset := (page - 1) * size
	query := models.DB.Model(&models.Goods{})
	var count int64
	query.Count(&count)
	name := c.GetString("name")
	if name != "" {
		query = models.DB.Model(&models.Goods{}).Where("name like ?", "%"+name+"%")
	}
	var goods []models.Goods
	query.Offset(offset).Limit(size).Find(&goods)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "分页成功",
		"data": map[string]interface{}{
			"count": count,
			"goods": goods,
		},
	}
	c.ServeJSON()
	return
}

// 删除
func (c *GoodsController) Delete() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	models.DB.Delete(&models.Goods{}, id)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
